<?php
namespace modules\comment;
use \phiction\exceptions\bad_request;
use \phiction\exceptions\denied as access_denied;
use \phiction\array_utils as arr;
use \modules\auth\api as auth;

class api
{
    static function list($q, &$args): array
    {
        $post = (int)arr::get_or_bad_request($args, 'post');
        $page = (int)arr::get_or_bad_request($args, 'page');
        return storage::list($q, $post, $page)->run();
    }

    static function delete($q, &$args)
    {
        $comment = (int)arr::get_or_bad_request($args, 'id');
        $shards = auth::validate($q, $args);
        $role = $shards['role'];
        $login = $shards['login'];

        if ($role !== 'admin') {
            $info = storage::author_login($q, $comment)->run();
            if (is_null($info)) throw new bad_request("cannot delete comment");

            $author_login = $info['login'];
            if ($login !== $author_login) throw new access_denied;
        }

        if (storage::delete($q, $comment)->run() !== 1)
            throw new bad_request("cannot delete comment");
    }

    static function add($q, &$args)
    {
        $post = (int)arr::get_or_bad_request($args, 'post');
        $body = arr::get_or_bad_request($args, 'body');
        $shards = auth::validate($q, $args);
        $author = $shards['id'];

        if (storage::add($q, $post, $body, $author)->run() !== 1)
            throw new bad_request("cannot add comment");
    }
}

